<template>
  <div class="app-container">
    <h2>学生活动记录</h2>

    <!-- 操作区域 -->
    <el-form :inline="true" :model="queryParams" label-width="100px">
      <el-form-item label="学生姓名">
        <el-input v-model="queryParams.studentName" placeholder="请输入学生姓名" />
      </el-form-item>
      <el-form-item label="活动名称">
        <el-input v-model="queryParams.activityName" placeholder="请输入活动名称" />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="handleQuery">查询</el-button>
        <el-button @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <!-- 数据表格 -->
    <el-table :data="tableData" border style="width: 100%">
      <el-table-column label="操作" width="100">
        <template #default="scope">
          <el-button
            type="danger"
            size="small"
            @click="handleDelete(scope.row.id)"
          >
            删除
          </el-button>
        </template>
      </el-table-column>
      <el-table-column prop="studentName" label="学生姓名" width="120" />
      <el-table-column prop="activityName" label="活动名称" width="150" />
      <el-table-column prop="status" label="状态" :formatter="formatStatus" width="100" />
      <el-table-column prop="point" label="积分" width="80" />

      <el-table-column prop="activityTime" label="活动时间" width="200" />
      <el-table-column
        :formatter="formatUpdateTime"
        label="报名时间"
        width="160"
      />
      <el-table-column
        prop="updateTime"
        :formatter="(row: any) => formatUpdateTime(row)"
        label="签到时间/取消时间"
        width="160"
      />

    </el-table>

    <el-pagination
      background
      layout="prev, pager, next"
      :total="total"
      :page-size="pageSize"
      @current-change="handlePageChange"
      style="margin-top: 20px; text-align: center"
    />
  </div>
</template>

<script lang="ts">
import { h } from 'vue';
import dayjs from 'dayjs';
import { defineComponent, ref, onMounted } from "vue";
import StudentActivityHistoryAPI from "@/api/student-activity-history";

const formatTime = (row: any) => {
  return row.createTime ? dayjs(row.createTime).format('YYYY-MM-DD HH:mm:ss') : '--';
};

export default defineComponent({
  name: "StudentActivityHistory",
  computed: {
    dayjs() {
      return dayjs
    }
  },
  setup() {

    const formatUpdateTime = (row: any) => {
      const time = row.updateTime ? dayjs(row.updateTime).format('YYYY-MM-DD HH:mm:ss') : '--';

      if (row.status === 3) {
        return h('span', { style: { color: 'red' } }, time);
      }

      return time;
    };


    const tableData = ref<any[]>([]);
    watchEffect(() => {
      console.log("tableData 更新了：", tableData.value);
    });

    const total = ref<number>(0);
    const pageSize = ref<number>(5);
    const currentPage = ref<number>(1);
    const queryParams = ref<{
      studentName: string;
      activityName: string;
    }>({
      studentName: "",
      activityName: ""
    });

    // 格式化状态字段
    const formatStatus = (row: any) => {
      const statusMap: Record<number, string> = {
        1: "未签到",
        2: "已签到",
        3: "已取消",
      };
      return statusMap[row.status] || "未知";
    };

    //获取所有记录（分页）
    const fetchData = async (pageNum: number) => {
      try {
        const res = await StudentActivityHistoryAPI.getPage(
                pageNum,
                pageSize.value,
                queryParams.value.studentName,
                queryParams.value.activityName
              );

        console.log("完整响应 res:", res); // 👈 添加这一行
        console.log("res.data 内容:", res.data); // 👈 添加这一行

        tableData.value = res.records || [];
        total.value = res.total || 0;



      } catch (error) {
        console.error("请求失败：", error);
      }
    };
    // const fetchData = async (pageNum: number) => {
    //   try {
    //     const res = await StudentActivityHistoryAPI.getPage(
    //       pageNum,
    //       pageSize.value,
    //       queryParams.value.studentName,
    //       queryParams.value.activityName
    //     );
    //
    //     console.log("完整响应 res:", res); // 调试用，可保留
    //     tableData.value = res || [];
    //     // total.value = res.total || 0;
    //
    //   } catch (error) {
    //     console.error("请求失败：", error);
    //   }
    // };

    // 查询按钮点击事件
    const handleQuery = () => {
      currentPage.value = 1;
      fetchData(currentPage.value);
    };

    // 重置查询条件
    const resetQuery = () => {
      queryParams.value.studentName = "";
      queryParams.value.activityName = "";
      fetchData(1);
    };

    // 分页切换
    const handlePageChange = (pageNum: number) => {
      fetchData(pageNum);
    };

    onMounted(() => {
      fetchData(1);
    });

    const handleDelete = async (id: number) => {
      try {
        await StudentActivityHistoryAPI.deleteRecord(id); // 调用删除接口
        ElMessage.success("删除成功");
        fetchData(currentPage.value); // 刷新当前页数据
      } catch (error) {
        console.error("删除失败：", error);
        ElMessage.error("删除失败");
      }
    };

    return {
      tableData,
      total,
      pageSize,
      currentPage,
      queryParams,
      formatStatus,
      formatUpdateTime,
      handleQuery,
      resetQuery,
      handlePageChange,
      handleDelete
    };
  },
});


</script>

<style scoped>
.app-container {
  padding: 20px;
}
</style>
